/**************************************************************************
 * @name: main.c
 * @brief: 主函数
 * @date:
 * @author: boluzs@163.com
 * @note: None
 * @version: 1.0.0
 *
 * Copyright (c) 2025 by boluzs@163.com, All Rights Reserved.
 **************************************************************************/
#include "main.h"
#include "start.h"
#include "bmp.h"
#include "menu.h"

unsigned int *lcd_buf;
unsigned int *lcd_mp;
Td_t touch_data;
pthread_t touch_thread;
pthread_t time_thread;
font *pft;
User_p login_user;
char *cur_datetime;

void *Touch_Task(void *arg)
{
	Get_Ts();
	return NULL;
}

void *Time_Task(void *arg)
{
	Get_Time();
	return NULL;
}

void Page_Manager(void)
{
	bool running = true; // 应用程序是否运行

	while (running)
	{
		switch (touch_data.page)
		{
		case MAIN_PAGE:
			Goto_Main_Page(); // 主页面逻辑
			break;

		case CHARGE_PAGE:
			Goto_Charge_Page(); // 充电模式页面
			break;

		case FAST_CHARGE_PAGE:
			Goto_Fast_Charge(); // 快充页面
			break;

		case SLOW_CHARGE_PAGE:
			Goto_Slow_Charge(); // 慢充页面
			break;

		case MONEY_PAGE:
			Goto_Money_Page(); // 充值缴费页面
			break;

		case ACCOUNT_PAGE:
			Goto_Account_Page(); // 账户页面
			break;

		case LOGIN_PAGE:
			Goto_Login_Page(); // 登录页面
			break;

		case REGISTER_PAGE:
			Goto_Register_Page(); // 注册页面
			break;

		case MENU_PAGE:
			Goto_User_Page(); // 用户菜单页面
			break;

		case ROLE_PAGE:
			Goto_Role_Page(); // 角色页面
			break;

		case PAGE_EXIT:
			running = false; // 设置 `running` 为 false 退出循环
			break;

		default:
			fprintf(stderr, "未知页面状态！退出程序。\n");
			running = false;
			break;
		}
	}
}

int main(int argc, char const *argv[])
{
	// 打开字库
	pft = fontLoad("/usr/share/fonts/DroidSansFallback.ttf");
	// 打开lcd屏文件
	int lcd_fd = open(LCD_DEV, O_RDWR);

	// 映射lcd文件到内存
	lcd_mp = (unsigned int *)mmap(NULL, LCD_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
								  lcd_fd, 0);
	if (lcd_mp == MAP_FAILED)
	{
		fprintf(stderr, "mmap lcd error,errno = %d,%s\n", errno, strerror(errno));
		exit(-1);
	}
	lcd_buf = (unsigned int *)calloc(1, LCD_SIZE);
	cur_datetime = (char *)calloc(1, 32);
	// 1.开机动画
	Start_Show(DIR_PATH, 0, 0);

	// 2.打开触摸屏，linux系统下把硬件设备抽象为文件，所以可以访问硬件设备的设备文件
	touch_data.ts_fd = open(TS_DEV, O_RDONLY | O_NONBLOCK);
	touch_data.page = ROLE_PAGE;
	// 创建触摸屏的线程
	pthread_create(&touch_thread, NULL, Touch_Task, &touch_thread);
	pthread_create(&time_thread, NULL, Time_Task, &time_thread);

	// 选择功能菜单
	Page_Manager();

	// 关闭文件和映射
	close(lcd_fd);
	close(touch_data.ts_fd);
	free(login_user);
	free(lcd_buf);
	free(cur_datetime);
	munmap(lcd_mp, LCD_SIZE);
	// 停止触摸屏线程
	touch_keep_running = false;
	pthread_cancel(touch_thread);
	return 0;
}